/**
 * Copyright (c) 2019 湖南牛数 All rights reserved.
 * <p>
 * https://www.dshubs.io
 * <p>
 * 版权所有，侵权必究！
 */

package io.dshubs.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.dshubs.archives.feign.ArchivesFeignClient;
import io.dshubs.commons.log.annotation.LogOperation;
import io.dshubs.commons.tools.constant.Constant;
import io.dshubs.commons.tools.page.PageData;
import io.dshubs.commons.tools.utils.Result;
import io.dshubs.commons.tools.validator.AssertUtils;
import io.dshubs.commons.tools.validator.ValidatorUtils;
import io.dshubs.commons.tools.validator.group.AddGroup;
import io.dshubs.commons.tools.validator.group.DefaultGroup;
import io.dshubs.commons.tools.validator.group.UpdateGroup;
import io.dshubs.dao.SysTenantDao;
import io.dshubs.dao.SysUserDao;
import io.dshubs.dto.SysTenantDTO;
import io.dshubs.entity.SysTenantEntity;
import io.dshubs.entity.SysUserEntity;
import io.dshubs.service.SysRoleUserService;
import io.dshubs.service.SysTenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 租户管理
 *
 * @author Mark sunlightcs@gmail.com
 */
@RestController
@RequestMapping("tenant")
@Api(tags = "租户管理")
public class SysTenantController {
    @Autowired
    private SysTenantService sysTenantService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    @Autowired
    private SysUserDao sysUserDao;

    @Autowired
    private SysTenantDao sysTenantDao;

    @Autowired
    private ArchivesFeignClient archivesFeignClient;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
            @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query", required = true, dataType = "int"),
            @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "tenantCode", value = "租户编码", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "tenantName", value = "租户名", paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "sysTenant", value = "是否查询系统租户 0：查询  其他值不查询", paramType = "query", dataType = "String")
    })
    @PreAuthorize("hasAuthority('sys:tenant:page')")
    public Result<PageData<SysTenantDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params) {
        PageData<SysTenantDTO> page = sysTenantService.page(params);

        return new Result<PageData<SysTenantDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @PreAuthorize("hasAuthority('sys:tenant:info')")
    public Result<SysTenantDTO> get(@PathVariable("id") Long id) {
        SysTenantDTO data = sysTenantService.get(id);

        //用户角色列表
        List<Long> roleIdList = sysRoleUserService.getRoleIdList(data.getUserId());
        data.setRoleIdList(roleIdList);

        return new Result<SysTenantDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @PreAuthorize("hasAuthority('sys:tenant:save')")
    public Result save(@RequestBody SysTenantDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);

        sysTenantService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @PreAuthorize("hasAuthority('sys:tenant:update')")
    public Result update(@RequestBody SysTenantDTO dto) {
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);

        sysTenantService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @PreAuthorize("hasAuthority('sys:tenant:delete')")
    public Result delete(@RequestBody Long[] ids) {
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        List<SysTenantEntity> tenantEntities = sysTenantDao.selectBatchIds(Arrays.asList(ids));
        sysTenantService.deleteBatchIds(Arrays.asList(ids));
        if(CollectionUtils.isNotEmpty(tenantEntities)) {
            List<Long> collect = tenantEntities.stream().map(SysTenantEntity::getTenantCode)
                    .collect(Collectors.toList());
            sysUserDao.delete(new QueryWrapper<SysUserEntity>()
                    .in("tenant_code",
                            collect));
            archivesFeignClient.deleteByCode(collect);
        }

        return new Result();
    }

    @GetMapping("listAll")
    @ApiOperation("返回所有租户信息")
    public Result listAll() {
        List<SysTenantEntity> list = sysTenantService.listAll();
        return new Result<List<SysTenantEntity>>().ok(list);
    }


    @GetMapping("/code/{tenantCode}")
    @ApiOperation("信息")
    public Result<SysTenantDTO> getTenantByCode(@PathVariable("tenantCode") Long tenantCode) {
        return new Result<SysTenantDTO>().ok(sysTenantService.getTenantCode(tenantCode));
    }
}